<?php

namespace app\adminapi\controller\v2;

use app\adminapi\controller\AuthController;
use app\model\admin\CompanyModel;
use app\model\admin\TrainTypeModel;
use app\model\course\topic\Topic;
use app\model\exam\Exam;
use app\model\exam\ExamLinkTopic;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;

class Test extends AuthController
{
    public function list(Request $request)
    {
        $limit = input('size', 10);
        $page = input('page', 1);

        $exam_name = input('exam_name', '');
        $type_id = input('type_id', '');
        $company_id = input('company_id', '');

        $data = Exam::order('id', 'desc')
            ->with('company')
            ->when($company_id || $company_id === 0, function ($query) use ($company_id) {
                $query->where('company_id', $company_id);
            })
            ->when($exam_name, function ($query) use ($exam_name) {
                $query->whereLike('exam_name', "%{$exam_name}%");
            })
            ->when($type_id, function ($query) use ($type_id) {
                $index = 0;
                foreach ($type_id as $typeID) {
                    if ($index == 0) {
                        $query->where('type_ids', 'like', "%,{$typeID},%");
                    } else {
                        $query->whereOr('type_ids', 'like', "%,{$typeID},%");
                    }
                    $index++;
                }
            })
            ->where('status', 1)
            ->paginate($limit)
            ->each(function ($item) {
                $typeIds = explode(',', $item['type_ids']);
                $types = TrainTypeModel::whereIn('id', $typeIds)
                    ->column('title');
                $item->type_name = implode(',', $types);
                $item->company_name = $item['company']['company_name'] ?? '平台';
            });

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total(),
        ]);
    }

    public function info(Request $request)
    {
        $train_types = DataType::getTrainType();
        $id = input('id', '');
        $dan_list = [];
        $duo_list = [];
        $pan_list = [];
        if ($id) {
            $data = Exam::where('id', $id)
                ->where('status', 1)
                ->find();
            if ($data->more_num > -1) {
                $data->more_num_count = $data->more_num;
                $data->more_num = 2;
            } else {
                $data->more_num = 1;
                $data->more_num_count = 1;
            }
            $data['selected_type_ids'] = DataType::getTrainTypeRelateIds($data['type_ids']);
            $data['type_ids'] = explode(',', trim($data['type_ids'], ','));
            $types = TrainTypeModel::whereIn('id', $data['type_ids'])
                ->column('title');
            $data['type_name'] = implode(',', $types);
            $dan_list = ExamLinkTopic::order('sort')
                ->where('exam_id', $id)
                ->withJoin('topic', 'LEFT')
                ->where('topic.type', 1)
                ->select()
                ->each(function ($item) {
                    $options2 = [];
                    if ($item['topic']) {
                        $options2[] = 'A.' . $item['topic']['a'];
                    }
                    if ($item['topic']) {
                        $options2[] = 'B.' . $item['topic']['b'];
                    }
                    if ($item['topic']) {
                        $options2[] = 'C.' . $item['topic']['c'];
                    }
                    if ($item['topic']) {
                        $options2[] = 'D.' . $item['topic']['d'];
                    }
                    $item['options2'] = $options2;
                    $item['id'] = $item['topic_id'];
                    if ($item['topic'] && $item['topic']['answer'] && is_array($item['topic']['answer'])) {
                        $item['answer'] = implode(',', $item['topic']['answer']);
                    } else {
                        $item['answer'] = $item['topic']['answer'] ?? '';
                    }
                    $item['title'] = $item['topic']['title'];
                    $item['type'] = $item['topic']['type'];
                    return $item;
                })
                ->toArray();
            $duo_list = ExamLinkTopic::order('sort')
                ->where('exam_id', $id)
                ->withJoin('topic', 'LEFT')
                ->where('topic.type', 2)
                ->select()
                ->each(function ($item) {
                    $options2 = [];
                    if ($item['topic']) {
                        $options2[] = 'A.' . $item['topic']['a'];
                    }
                    if ($item['topic']) {
                        $options2[] = 'B.' . $item['topic']['b'];
                    }
                    if ($item['topic']) {
                        $options2[] = 'C.' . $item['topic']['c'];
                    }
                    if ($item['topic']) {
                        $options2[] = 'D.' . $item['topic']['d'];
                    }
                    $item['options2'] = $options2;
                    $item['id'] = $item['topic_id'];
                    if ($item['topic'] && $item['topic']['answer'] && is_array($item['topic']['answer'])) {
                        $item['answer'] = implode(',', $item['topic']['answer']);
                    } else {
                        $item['answer'] = $item['topic']['answer'] ?? '';
                    }
                    $item['title'] = $item['topic']['title'];
                    $item['type'] = $item['topic']['type'];
                    return $item;
                })
                ->toArray();
            $pan_list = ExamLinkTopic::order('sort')
                ->where('exam_id', $id)
                ->withJoin('topic', 'LEFT')
                ->where('topic.type', 3)
                ->select()
                ->each(function ($item) {
                    $options2 = [];
                    if ($item['topic']) {
                        $options2[] = 'A.' . $item['topic']['a'];
                    }
                    if ($item['topic']) {
                        $options2[] = 'B.' . $item['topic']['b'];
                    }
                    if ($item['topic']) {
                        $options2[] = 'C.' . $item['topic']['c'];
                    }
                    if ($item['topic']) {
                        $options2[] = 'D.' . $item['topic']['d'];
                    }
                    $item['options2'] = $options2;
                    $item['id'] = $item['topic_id'];
                    if ($item['topic'] && $item['topic']['answer'] && is_array($item['topic']['answer'])) {
                        $item['answer'] = implode(',', $item['topic']['answer']);
                    } else {
                        $item['answer'] = $item['topic']['answer'] ?? '';
                    }
                    $item['title'] = $item['topic']['title'];
                    $item['type'] = $item['topic']['type'];
                    return $item;
                })
                ->toArray();
        } else {
            $data = null;
        }
        // 所有的公司
        $companies = \app\model\company\Company::where('status', 1)
            ->select()
            ->toArray();
        array_unshift($companies, [
            'id' => 0,
            'company_name' => '平台',
        ]);
        return app('json')->success(compact('train_types', 'data',
            'dan_list', 'duo_list', 'pan_list', 'companies'));
    }

    public function save(Request $request)
    {
        $param = $request->only([
            'exam_name', 'min_point', 'more_num', 'more_num_count', 'dan_num', 'dan_point',
            'duo_num', 'duo_point', 'pan_num', 'pan_point', 'type_ids'
        ]);
        $id = input('id', '');
        try {
            validate([
                'exam_name|试卷名称' => 'require|max:50',
                'min_point|及格分数' => 'require|number|gt:0',
                'more_num|不合格补考次数' => 'require|in:1,2',
                'dan_num|单选题数量' => 'require|number',
                'dan_point|单选题分数' => 'require|number',
                'duo_num|多选题数量' => 'require|number',
                'duo_point|多选题分数' => 'require|number',
                'pan_num|判断题数量' => 'require|number',
                'pan_point|判断题分数' => 'require|number',
            ])->check($param);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }
        if ($param['more_num'] == 1) {
            $param['more_num'] = -1;
        } else {
            $param['more_num'] = $param['more_num_count'];
        }
        unset($param['more_num_count']);
        $param['type_ids'] = ',' . implode(',', $param['type_ids']) . ',';
        if (
            (int)$param['dan_num'] * (int)$param['dan_point']
            + (int)$param['duo_num'] * (int)$param['duo_point']
            + (int)$param['pan_num'] * (int)$param['pan_point'] != 100) {
            return app('json')->fail('请重新设置题目数和分值，当前总分不等于100');
        }
        $dan = Topic::where('type', 1)
            ->where('resource_type', 2)
            ->where('status', 1)
            ->orderRaw('rand()')
            ->limit($param['dan_num'] ?? 0)
            ->select()
            ->toArray();
        if (count($dan) != $param['dan_num']) {
            return  app('json')->fail('单选题数量不足');
        }
        $duo = Topic::where('type', 2)
            ->where('resource_type', 2)
            ->where('status', 1)
            ->orderRaw('rand()')
            ->limit($param['duo_num'] ?? 0)
            ->select()
            ->toArray();
        if (count($duo) != $param['duo_num']) {
            return  app('json')->fail('多选题数量不足');
        }
        $pan = Topic::where('type', 3)
            ->where('resource_type', 2)
            ->where('status', 1)
            ->orderRaw('rand()')
            ->limit($param['pan_num'] ?? 0)
            ->select()
            ->toArray();
        if (count($pan) != $param['pan_num']) {
            return  app('json')->fail('判断题数量不足');
        }

        if (!$id) {
            $res = Exam::create($param);
            $id = $res->id;
        } else {
            Exam::update($param, [
                'id' => $id,
            ]);
            ExamLinkTopic::where('exam_id', $id)
                ->delete();
        }
        $insertData = [];
        $index = 1;
        foreach ($dan as $item) {
            $insertData[] = [
                'exam_id' => $id,
                'topic_id' => $item['id'],
                'sort' => $index++,
            ];
        }
        $index = 1;
        foreach ($duo as $item) {
            $insertData[] = [
                'exam_id' => $id,
                'topic_id' => $item['id'],
                'sort' => $index++,
            ];
        }
        $index = 1;
        foreach ($pan as $item) {
            $insertData[] = [
                'exam_id' => $id,
                'topic_id' => $item['id'],
                'sort' => $index++,
            ];
        }
        (new Examlinktopic)->saveAll($insertData);
        return app('json')->success();
    }

    public function savetopic(Request $request)
    {
        $param = $request->only([
            'id', 'dan_list', 'duo_list', 'pan_list',
        ]);
        try {
            validate([
                'id|ID参数' => 'require',
                'dan_list|单选题' => 'array',
                'duo_list|多选题' => 'array',
                'pan_list|判断题' => 'array',
            ])->check($param);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }
        $insertData = [];
        $index = 0;
        $dan_count = 0;
        $duo_count = 0;
        $pan_count = 0;
        foreach ($param['dan_list'] ?? [] as $item) {
            $insertData[] = [
                'exam_id' => $param['id'],
                'topic_id' => $item['id'],
                'sort' => $index++,
            ];
            $dan_count++;
        }
        $index = 0;
        foreach ($param['duo_list'] ?? [] as $item) {
            $insertData[] = [
                'exam_id' => $param['id'],
                'topic_id' => $item['id'],
                'sort' => $index++,
            ];
            $duo_count++;
        }
        $index = 0;
        foreach ($param['pan_list'] ?? [] as $item) {
            $insertData[] = [
                'exam_id' => $param['id'],
                'topic_id' => $item['id'],
                'sort' => $index++,
            ];
            $pan_count++;
        }
        // 比对数量
        $test = Exam::where('id', $param['id'])
            ->find();
        if ($test['dan_num'] != $dan_count) {
            return app('json')->fail('请重新设置题目数，当前单选数量不等于数据库数量');
        }
        if ($test['duo_num'] != $duo_count) {
            return app('json')->fail('请重新设置题目数，当前多选数量不等于数据库数量');
        }
        if ($test['pan_num'] != $pan_count) {
            return app('json')->fail('请重新设置题目数，当前判断数量不等于数据库数量');
        }

        ExamLinkTopic::where('exam_id', $param['id'])
            ->delete();
        (new ExamLinkTopic())->saveAll($insertData);
        return app('json')->success();
    }

    public function randomtopic(Request $request)
    {
        $param = $request->only(['dan' => '', 'duo' => '', 'pan' => '']);
        $dan = [];
        $duo = [];
        $pan = [];
        if ($param['dan'] !== '') {
            $dan = Topic::where('type', 1)
                ->where('status', 1)
                ->orderRaw('rand()')
                ->limit($param['dan'])
                ->select()
                ->toArray();
        }
        if ($param['duo'] !== '') {
            $duo = Topic::where('type', 2)
                ->where('status', 1)
                ->orderRaw('rand()')
                ->limit($param['duo'])
                ->select()
                ->toArray();
        }
        if ($param['pan'] !== '') {
            $pan = Topic::where('type', 3)
                ->where('status', 1)
                ->orderRaw('rand()')
                ->limit($param['pan'])
                ->select()
                ->toArray();
        }
        return app('json')->success([
            'dan' => $dan,
            'duo' => $duo,
            'pan' => $pan,
        ]);
    }

    public function delete(Request $request)
    {
        $id = input('id', '');
        Exam::dataDelete($id);
        return app('json')->success();
    }
}